//
//  NoticeMessageViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/8.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "NoticeMessageViewController.h"
#import "NoticeMessageTableViewCell.h"
#import "WebDetailInfoViewController.h"
static NSString * cellIndentifier = @"NoticeMessageTableViewCell";

@interface NoticeMessageViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray * noticeArray;

@end

@implementation NoticeMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _noticeArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}
- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self.tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.scrollEnabled = YES;

}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getNoticeInfo];
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.noticeArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getNoticeInfo];
        });
    }
    
}



#pragma  mark == 获取消息数据
- (void)getNoticeInfo{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    [dic setObject:@"1" forKey:@"meType"];
    NSString *userId = @"";
    if ([Common getLoginStatus]) {
        NSDictionary * dic1 =  [Common getLoginInfo];
        userId = dic1[@"userId"];
    }
    [dic setObject:userId forKey:@"userId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryNotificationMessageAll withHttpType:@"POST" withTag:SX_SX_queryNotificationMessageAll];
    
}


#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 116*VerticalRatio();
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _noticeArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NoticeMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    if (cell == nil) {
        cell= [[NoticeMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }

    cell.noticeTitle.frame = flexibleFrame(CGRectMake(27, 23, 266, 15), YES);
    cell.noticeTitle.numberOfLines = 0;
    cell.noticeInfo.frame = flexibleFrame(CGRectMake(27, 43, 274, 15), YES);
    cell.noticeInfo.numberOfLines = 0;
    cell.noticeTitle.text = [NSString stringWithFormat:@"%@",_noticeArray[indexPath.row][@"mmmeTitle"]];
    cell.noticeInfo.text  = [NSString stringWithFormat:@"%@",_noticeArray[indexPath.row][@"mmmeContent"]];
    [cell.noticeInfo sizeToFit];
    [cell.noticeTitle sizeToFit];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[_noticeArray[indexPath.row][@"mmmeCreateDate"] integerValue]/1000];
    cell.timeLabel.text = [formatter stringFromDate:confromTimesp];
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"PersonCenterStoryboard" bundle:nil];
    WebDetailInfoViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"WebDetailInfo"];
    page.objectId = _noticeArray[indexPath.row][@"mmmeId"];
    page.titleStr = @"通知消息";
    page.meType = @"1";
    [self.navigationController  pushViewController:page animated:YES];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag == SX_SX_queryNotificationMessageAll){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.noticeArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.noticeArray addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });

            
        }
        
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
